package com.augurit.gzcgwsp.ywcmn.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.webservice.SFTPUtil;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComPrintService;
import com.augurit.gzcgwsp.ywcmn.service.IYwDzgzListService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComPrintForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwDzgzListForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.service.IWfTemplateAttachmentRefService;
import com.augurit.wf.bi.web.form.WfTemplateAttachmentRefForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.WfBusInstance;

@SuppressWarnings("serial")
@Results({
    @Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/ywcmn/YwComPrint/yw-print.jsp"),
    @Result(name = "DBLCLICK_WIN", location = "/gzcgwsp/ywcmn/YwComPrint/yw_print-win.jsp"),
    @Result(name = "DZGZCLICK_WIN", location = "/common/apabiPrint/yw_print-win.jsp"),
    @Result(name = "PRINT_WIN", location = "/gzcgwsp/ywcmn/YwComPrint/yw_pwin.jsp"),
    @Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP)
})
public class YwComPrintAction extends ExtCrudActionSupport<YwComPrintForm> {
	@Autowired
	private IYwPrintDocService ywPrintDocService;	//公告板service类
	private static final int FILE_SIZE=16*1024;
    @Autowired
    private IYwComPrintService ywComPrintService;
	private File attach;//附件
	private String attachFileName;//附件名称
	@Autowired
	private IYwDzgzListService ywDzgzListService;
	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplatePrintRefServiceEX;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    
    @Autowired
    private IWfTemplateAttachmentRefService wfTemplateAttachmentRefService;
    
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
    
    private YwComPrintForm form;
    private Page<YwComPrintForm> page = new Page<YwComPrintForm>(15);
    private Page<WfTemplateAttachmentRefForm> tplpage = new Page<WfTemplateAttachmentRefForm>(10);
    private boolean suitPrint = false;//标志是否为套打
    public String printData() throws Exception {
        ExtUtils.initPageFromExtGridParam(getRequest(), page);
        ywComPrintService.getPrintDataList(page, form);
        renderText(Struts2Utils.getJsonString(page, DateUtils.YEAR_MOUTH_DAY_));
        return null;
    }
    
    public String printList() throws Exception {
        String activityName=getRequest().getParameter("activityName");
        ExtUtils.initPageFromExtGridParam(getRequest(), tplpage);
        wfTemplateAttachmentRefServiceEX.searchAvailablePrintTemplate(tplpage, form,activityName);
        translateList(tplpage.getResult());
        renderText(Struts2Utils.getJsonString(tplpage, DateUtils.YEAR_MOUTH_DAY_));
        
        return null;
    }
    
    //获取request对象中所有参数，并设置到map中
    private  Map getMapByRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = request.getParameterNames();
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            String paraValue = request.getParameter(paraName).trim(); 
            if(paraValue!=null && !"".equals(paraValue)){
                map.put(paraName, paraValue);
            }
        }  
        return map;
    }	
		
    
	/**
	 * 上传附件
	 * @return
	 * @throws IOException 
	 */
	public String  uploadAttach() throws IOException{
		    Map map=getMapByRequest(getRequest());
		    String ajid=(String) map.get("ajid");
		    String attacheName=(String) map.get("attacheName");
		    String templateCode=(String) map.get("templateCode");
		    YwDzgzListForm gzform=ywDzgzListService.getFromByCode(Long.valueOf(ajid),templateCode,attacheName);
			if(gzform==null){
				gzform=new YwDzgzListForm();
			}
			LoginUserForm loginUser = (LoginUserForm) getRequest().getSession()
			.getAttribute(WebContextUtils.SES_LOGIN_USER);
				// 随机生成文件名后缀
			String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			int random = new Random().nextInt(1000000);
			String context =getRequest().getSession()
						.getServletContext().getRealPath("");
			try {
				if(this.attach!=null){
					String filetype=this.attachFileName.substring(attachFileName.lastIndexOf(".")+1,attachFileName.length());
					String filename=formatDate+random+"."+filetype;
					String directory=context+File.separator+"resources"+File.separator+"AttacheFile";
					String uploadPath=directory+File.separator+filename;
					String filepath="/resources/AttacheFile/"+filename;
					File targetFile=new File(uploadPath);
					upLoadFile(attach,targetFile);
					//同时上传一份到另外一台服务器
					SFTPUtil.uploadOtherFile(filepath, uploadPath);
					logger.info("附件上传到另外一台机器---------->"+filename);
					gzform.setAjid(Long.valueOf(ajid));
					gzform.setFilename(attacheName);
					gzform.setTemplateCode(templateCode);
					gzform.setFilepath(filepath);
					gzform.setFiletype(filetype);
					gzform.setUsername(loginUser.getUser().getUserName());;
					gzform.setUploaddate(new Date());
					ywDzgzListService.save(gzform);
				}
				 JSONObject jsonObject = JSONObject.fromObject(form); 
				 getResponse().setContentType("text/html;charset=UTF-8");
				 getResponse().getWriter().print("<script type='text/javascript'>parent.resultValue('"+jsonObject.toString()+"');</script>");
			} catch (RuntimeException e) {
				e.printStackTrace();
				 getResponse().setContentType("text/html;charset=UTF-8");
				 getResponse().getWriter().print("<script type='text/javascript'>parent.resultValue('{success:true,msg:false}');</script>");
				
			}
			
			
			 
			 return null;
	}

	
	 public void upLoadFile(File source,File target){
		  InputStream in=null;
		  OutputStream out=null;
		  try{
		   in=new BufferedInputStream(new FileInputStream(source),FILE_SIZE);
		   out=new BufferedOutputStream(new FileOutputStream(target),FILE_SIZE);
		   byte[] image=new byte[FILE_SIZE];
		   while(in.read(image)>0){
		    out.write(image);
		   }
		  }catch(IOException ex){
		   ex.printStackTrace();
		  }finally{
		   try{
		    in.close();
		    out.close();
		   }catch(IOException ex){
		    
		   }
		  }
		 }
	
	
    public String getList() throws Exception {
        ExtUtils.initPageFromExtGridParam(getRequest(), tplpage);
        ywComPrintService.getPrintTplList(page, form);
        renderText(Struts2Utils.getJsonString(page, DateUtils.YEAR_MOUTH_DAY_));
        
        return null;
    }
    
    //rqssgd dzgz //rqjyxkz_gdqy dzgz //rqjyxkz_pzqy dzgz //rqrsqjazwxqyzz dzgz
    public String taskInfo() throws Exception {
        return "PRINT_WIN";
    }
    
    public String info() throws Exception {
    	if(("dzgz".equals(form.getActivityName()) && "rqjyxkz_gdqy".equals(form.getTemplateCode()))
    		|| ("dzgz".equals(form.getActivityName()) && "rqjyxkz_pzqy".equals(form.getTemplateCode()))
    		|| ("dzgz".equals(form.getActivityName()) && "rqrsqjazwxqyzz".equals(form.getTemplateCode())) 
    		|| ("dzgz".equals(form.getActivityName()) && "hwggshsqb".equals(form.getTemplateCode()))
    		|| ("jbrsj".equals(form.getActivityName()) && "hwggshsqb".equals(form.getTemplateCode()))
    		||("jbrsj".equals(form.getActivityName()) && "rqrsqjazwxqyzz".equals(form.getTemplateCode()))
    	
    	){
    		suitPrint = true;
    	}
    	String templateCode=getRequest().getParameter("templateCode");
		String ywId=getRequest().getParameter("ywId");
    	
    	
        return "DBLCLICK_WIN";
    }
    //电子盖章
    public String dzgz() throws Exception {
    	String templateCode=getRequest().getParameter("templateCode");
		String ywId=getRequest().getParameter("id");
    	if(("dzgz".equals(form.getActivityName()) && "rqjyxkz_gdqy".equals(form.getTemplateCode()))
    			|| ("dzgz".equals(form.getActivityName()) && "rqjyxkz_pzqy".equals(form.getTemplateCode()))
    			|| ("dzgz".equals(form.getActivityName()) && "rqrsqjazwxqyzz".equals(form.getTemplateCode()))
    			|| ("dzgz".equals(form.getActivityName()) && "hwggshsqb".equals(form.getTemplateCode()))
    			|| ("jbrsj".equals(form.getActivityName()) && "hwggshsqb".equals(form.getTemplateCode()))){
    		suitPrint = true;
    	}
    	
    	List<YwPrintDocForm> list=null;
		List<YwPrintDocForm> resultList=new ArrayList<YwPrintDocForm>();
		String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		if(StringUtils.isNotBlank(ywId)){
			list=ywPrintDocService.getByYwid(Long.valueOf(ywId),templateCode);
			WfBusInstance inst=this.ywPrintDocService.getWfBusInstance(templateCode, Long.valueOf(ywId));
			String sqdw=inst.getBusMemo1();
			String acceptNo=inst.getBusMemo3();
			if(list!=null && list.size() > 0){
				for(YwPrintDocForm form:list){
					Long templateId = wfBusTemplateService.getByTemplateCode(templateCode).getId();
			    	WfTemplateAttachmentRefFormEX refform=wfTemplatePrintRefServiceEX.getFormByCode(form.getFileCode(),templateId);
					String fileName=refform.getFileName();
					form.setFileName(fileName);
					//String realname=fileName.substring(0,fileName.indexOf("."));
					YwDzgzListForm gzForm=ywDzgzListService.getFromByCode(Long.valueOf(ywId), templateCode, fileName);
					if(gzForm!=null){
						form.setGzdate(gzForm.getUploaddate());
						form.setGzname(gzForm.getUsername());
						form.setGzpath(gzForm.getFilepath());
					}
					form.setGzName(acceptNo+sqdw+fileName);
					form.setFileName(fileName);
					resultList.add(form);
				}
			}
		
		}
		getRequest().setAttribute("resultList", resultList);
    	return "DZGZCLICK_WIN";
    }
    
    
    /**
     * 文书的创建人和创建时间还无加上，需要加上
     * @param result
     */
    private void translateList(List<WfTemplateAttachmentRefForm> list) {
      if(list!=null && list.size()>0){
          for(WfTemplateAttachmentRefForm reForm:tplpage.getResult()){
              if(reForm.getCreateTime()==null || StringUtils.isBlank(reForm.getCreator())){
                  ywComPrintService.translateList(reForm,form);
              }
          }
      }
        
    }
    
    /**
     * 检查文件
     * @return
     * @throws IOException 
     */
    public String checkFile() throws IOException{
    	String url=getParameter("url");
    	String realpath=getRequest().getSession().getServletContext().getRealPath("");
    	if(StringUtils.isNotBlank(url)){
    		realpath+=url;
    		realpath.replace("/", File.separator);
    		File file=new File(realpath);
    		if(file.exists()){
    			getResponse().getWriter().print("true");
    		}
    	}
    	
    	return null;
    }
    
   
    
    /**
     * 查看盖章的文件
     * @return
     * @throws IOException 
     */
    public String veiwGzfile() throws IOException{
    	String ywId=getParameter("ywId");
    	String filename=getParameter("filename");
    	String templateCode=getParameter("templateCode");
    	String realpath=getRequest().getSession().getServletContext().getRealPath("");
    	YwDzgzListForm dzform=this.ywDzgzListService.getFromByCode(Long.valueOf(ywId), templateCode, filename);
    	if(dzform!=null && StringUtils.isNotBlank(dzform.getFilepath())){
    		String url=dzform.getFilepath();
    		if(StringUtils.isNotBlank(url)){
        		realpath+=url;
        		realpath.replace("/", File.separator);
        		File file=new File(realpath);
        		if(file.exists()){
        			getResponse().getWriter().print(url);
        		}
        	}
    	}
    	
    	
    	return null;
    }
    
    
    
    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String list() throws Exception {
        return CrudActionSupport.SUCCESS;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (form == null) form = new YwComPrintForm();
    }

    @Override
    public String save() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    public YwComPrintForm getModel() {
        // TODO Auto-generated method stub
        return form;
    }

	public boolean isSuitPrint() {
		return suitPrint;
	}

	public void setSuitPrint(boolean suitPrint) {
		this.suitPrint = suitPrint;
	}

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}

}
